package main

import (
	"flag"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
	"strings"
)

var (
	endpoint   = "https://oss-cn-shanghai.aliyuncs.com"
	ak         = "LTAI5tCNUq8kT3Qm3heNg8iy"
	sk         = "hTXa2XWYIDwmT57KslZ30pv5oLeLTU"
	bucketName = "lwq-oss-repo"
	filePath   = "go.mo"
)

var (
	help bool
)

func usage() {
	fmt.Fprintf(os.Stderr, `upload-oss-tools version:v1.0.1
Usage: upload-oss-tools [-h] -f <upload_file_path>
Options:
`)
	flag.PrintDefaults()
}

func init() {
	flag.BoolVar(&help, "h", false, "help usage")
	flag.StringVar(&filePath, "f", "", "upload file path")
	flag.StringVar(&filePath, "s", "", "search file name")
}

func loadParam() error {
	flag.Parse()
	if help {
		usage()
		os.Exit(0)
	}

	return nil
}

func getObjectsFormResponce(lor oss.ListObjectsResult) string {
	var output string
	for _, object := range lor.Objects {
		output += object.Key + " "
	}
	return output
}

func Upload(filePath string) error {
	client, err := oss.New(endpoint, ak, sk)
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}

	//上传文件
	fileSplit := strings.Split(filePath, "/")
	fileName := fileSplit[len(fileSplit)-1]
	err = bucket.PutObjectFromFile(fileName, filePath)
	if err != nil {
		return err
	}

	//打印下载URL
	signUrl, err := bucket.SignURL("sdd.mod", oss.HTTPGet, 60*60*24)
	if err != nil {
		return fmt.Errorf("sign file download error,%s", err)
	}
	fmt.Printf("下载链接: %s\n", signUrl)
	fmt.Println("\n注意: 文件下载有效期1天，中转站保存时间3天")

	lor, err := bucket.ListObjects()
	if err != nil {
		return fmt.Errorf("%s", err)
	}
	fmt.Println(getObjectsFormResponce(lor))
	return nil
}

func validate() error {
	if endpoint == "" {
		return fmt.Errorf("endpoint is missed")
	}
	if ak == "" || sk == "" {
		return fmt.Errorf("ak or sk missed")
	}
	if filePath == "" {
		return fmt.Errorf("upload file missed")
	}
	return nil
}

func main() {
	loadParam()

	if err := validate(); err != nil {
		fmt.Printf("validate param error,%s\n", err)
		os.Exit(1)
	}

	if err := Upload(filePath); err != nil {
		fmt.Printf("upload file error,%s\n", err)
		os.Exit(1)
	}
	fmt.Printf("upload file: %s success", filePath)
}
